package com.xs.shop.marketing.service.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xs.shop.common.Result;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.marketing.model.entity.Activity;
import com.xs.shop.marketing.model.entity.PointLog;
import com.xs.shop.marketing.model.vo.PointLogListVO;
import com.xs.shop.marketing.service.handlers.BaseContextHandler;
import com.xs.shop.marketing.service.mapper.PointLogMapper;
import com.xs.shop.marketing.service.service.PointLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.user.feign.api.UserClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xs
 * @since 2025-07-20
 */
@Slf4j
@Service
public class PointLogServiceImpl extends ServiceImpl<PointLogMapper, PointLog> implements PointLogService {

    @Resource
    private UserClient userClient;

    @Override
    public PointLog addPointLog(PointLog pointLog) {
        // 设置默认值
        pointLog.setCreatedAt(LocalDateTime.now());
        pointLog.setUpdatedAt(LocalDateTime.now());

        Long adminId = BaseContextHandler.get();
        if (adminId != null) {
            pointLog.setCreatedBy(adminId);
            pointLog.setUpdatedBy(adminId);
        }
        this.save(pointLog);
        return pointLog;
    }

    @Override
    public Boolean deletePointLog(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }

    @Override
    public PointLog updatePointLog(PointLog pointLog) {
        if (pointLog == null || pointLog.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        pointLog.setUpdatedAt(LocalDateTime.now());
        pointLog.setUpdatedBy(BaseContextHandler.get());
        this.updateById(pointLog);
        return pointLog;
    }

    @Override
    public IPage<PointLogListVO> pageQuery(Integer current, Integer pageSize, Integer status) {
        // 根据线程中存的的memberid去point_log表查，
        Long memberId = BaseContextHandler.get();
        if (memberId == null) {
            throw new BusinessException(Resp.MEMBER_NOT_EXIST);
        }
        LambdaQueryWrapper<PointLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PointLog::getMemberId, memberId)
                .orderByDesc(PointLog::getCreatedAt);
        if(status != null){
            wrapper.eq(PointLog::getStatus, status);
        }

        Page<PointLog> page = this.page(new Page<>(current, pageSize), wrapper);

        IPage<PointLogListVO> pageVO = new Page<>();
        BeanUtils.copyProperties(page, pageVO);

        List<PointLog> records = page.getRecords();
        List<PointLogListVO> pointLogListVOList = new ArrayList<>();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for(PointLog pointLog : records){
            PointLogListVO pointLogListVO = new PointLogListVO();
            BeanUtils.copyProperties(pointLog, pointLogListVO);
            log.info("point record date:{}", pointLog.getCreatedAt());
            // 转换时间字符串
            if (pointLog.getCreatedAt() != null) {
                String dateStr = pointLog.getCreatedAt().format(formatter);
                pointLogListVO.setCreatedAt(dateStr); // 假设有 dateStr 字段
            }
            pointLogListVOList.add(pointLogListVO);
        }

        pageVO.setRecords(pointLogListVOList);
        return pageVO;
    }

    @Override
    public Integer getTotalPoint() {
        log.info("userClient返回的值：{}",userClient.getMemberTotalPoint(BaseContextHandler.get()).getData());
        return userClient.getMemberTotalPoint(BaseContextHandler.get()).getData();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createPointLogWhenMemberAct(Integer value, Integer status, String intro) {
        Long memberId = BaseContextHandler.get();
        if (memberId == null) {
            throw new BusinessException(Resp.MEMBER_NOT_EXIST);
        }
        PointLog pointLog = new PointLog();
        pointLog.setMemberId(memberId);
        pointLog.setCreatedAt(LocalDateTime.now());
        pointLog.setStatus(status);
        pointLog.setValue(value);
        pointLog.setIntro(intro);
        this.save(pointLog);

        Result<Boolean> booleanResult = userClient.updatePointWhenMemberAct(value,status);
        Boolean res = booleanResult.getData();
        if(!res){
            throw new BusinessException(Resp.FAIL);
        }

        return true;
    }

}
